import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import CommentForm from "../components/Comment/CommentForm";
import {addComment} from '../reducers/comments'

class CommentFormContainer extends Component {
  static propTypes = {
    comments: PropTypes.array,
    onAddComment: PropTypes.func
  }

  constructor(props) {
    super(props);
    this.state = {
      user: null
    }
  }

  componentWillMount() {
    this._loadUser()
  }

  _loadUser() {
    const user = localStorage.getItem('user')
    if (user) {
      this.setState({
        user
      })
    }
  }

  _saveUser(user) {
    localStorage.setItem('user', user)
  }

  handleAddComment(comment) {
    this._saveUser(comment.user);
    const {comments} = this.props;
    const newComments = [...comments, comment]
    localStorage.setItem('comments', JSON.stringify(newComments));
    if (this.props.onAddComment) {
      this.props.onAddComment(comment)
    }
  }

  render() {
    return (
        <CommentForm user={this.state.user} onSubmit={this.handleAddComment.bind(this)}></CommentForm>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    comments: state.comments
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onAddComment: (comment) => {
      dispatch(addComment(comment))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(CommentFormContainer);
